<template>
  <transition>
    <div v-if="visible" class="detail-main">
      <el-page-header @back="handleClose" :icon="null" class="detail-header">
        <template #title>
          <div class="detail-header-title">
            {{props.id ? '编辑' : '新增'}}
          </div>
        </template>
        <template #content>
          菜单信息
        </template>
        <template #extra>
          <div style="flex: auto">
            <el-button type="primary" @click="handleOk(formRef)" :loading="state.subLoading" :icon="Select">
              保存
            </el-button>
            <el-button @click="handleClose" :icon="Back">返回列表</el-button>
          </div>
        </template>
      </el-page-header>
      <div class="detail-form">
        <el-form ref="formRef" :model="formState" label-width="auto" :rules="rules" v-loading="state.subLoading">
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="parentName" label="上级菜单">
                <el-cascader id="parentId" v-model="defaultParentIds" :options="menuTreeOptions" :props=fieldNames
                             placeholder="请选择上级菜单" change-on-select clearable class="w-500"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item label="菜单类型" prop="type">
                <el-select id="grade" v-model="formState.type" placeholder="请选择菜单类型" class="w-500" clearable>
                  <el-option :value="0" label="目录" />
                  <el-option :value="1" label="菜单" />
                  <el-option :value="2" label="按钮" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="name" label="菜单名称">
                <el-input id="name" v-model="formState.name" placeholder="请输入菜单名称" class="w-500" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="icon" label="菜单图标">
                <icon-picker :icon="formState.icon" @updateIcon="handleUpdateIcon">
                  <template #default>
                    <el-input v-model="formState.icon" class="w-500">
                      <template #prefix>
                        <svg-icon
                            v-if="formState.icon"
                            :icon-class="formState.icon"
                            style="font-size: 16px; min-width: 16px"
                        />
                      </template>
                    </el-input>
                  </template>
                </icon-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="path" label="路由路径">
                <el-input id="path" v-model="formState.path" placeholder="请输入路由路径" class="w-500" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="routerUrl" label="组件路径">
                <el-input id="component" v-model="formState.component" placeholder="请输入组件路径" class="w-500" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="sort" label="排序">
                <el-input id="sort" :min="1"  v-model="formState.sort" placeholder="请输入排序" type="number" class="w-500" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="enabled" label="启用状态">
                <el-checkbox v-model="formState.enabled"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </transition>
</template>

<script setup name="MenuDetail">
import {MenuApi} from '@/api/system/menu';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import {detailState, pageSearch, setSubLoading, state} from "../index";
import iconPicker from "@/components/IconPicker/index.vue";
import {rules} from "@/views/system/menu/index";
import { Back, Select } from '@element-plus/icons-vue'
import SvgIcon from "@/components/SvgIcon/index.vue";
import {Utils} from "@/utils/index.js";

const {proxy} = useCurrentInstance();
const emits = defineEmits(["refreshData"]);
let formState = toRef(detailState);
const formRef = ref();
const menuTreeOptions = ref([]);
const defaultParentIds = ref([]);
const fieldNames = {
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true
}
const visible = ref(false)
const props = defineProps({
  id: {
    type: String,
    required: false,
  },
  drawer: {
    type: Boolean,
    required: true,
  }
});

function handleUpdateIcon(icon) {
  formState.value.icon = icon;
}

//保存
function handleOk(formEl) {
  if (defaultParentIds.value && defaultParentIds.value.length > 0) {
    formState.value.parentId = defaultParentIds.value[defaultParentIds.value.length - 1];
  } else {
    formState.value.parentId = 0;
  }
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      setSubLoading(true);
      if (formState.value.id) {
        MenuApi.update(formState.value).then(res => {
          if (res.success) {
            proxy.$message.success(res.message);
            handleClose()
          } else {
            proxy.$message.error(res.message);
          }
        });
      } else {
        MenuApi.save(formState.value).then(res => {
          if (res.success) {
            proxy.$message.success(res.message);
            handleClose()
          } else {
            proxy.$message.error(res.message);
          }
        });
      }
      setSubLoading(false);
    } else {
      console.log('error submit!', fields)
    }
  })
}

//关闭弹窗
function handleClose() {
  formRef.value?.resetFields();
  resetData();
  emits('refreshData');
}

//重置数据
function resetData() {
  defaultParentIds.value = [];
  formState.value = detailState;
  formState.value.grade = 1;
  formState.value.parentId = null;
}

//查询菜单树
const getMenuTree = (id) => {
  const pageSearch = {
    pageNumber: 1,
    pageSize: 1000,
    partitionId: id,
    parentId: 0
  }
  MenuApi.findPage(pageSearch)
      .then(res => {
        if (res.success) {
          menuTreeOptions.value = Utils.convertTreeData(res.data.records);
        }
      }).catch(() => {
  });
};

//初始化数据
function initInfo(save, parentInfo) {
  setSubLoading(true);
  getMenuTree(pageSearch.partitionId).then(() => {
    if (parentInfo) {
      if (parentInfo.treePath) {
        let treePath = parentInfo.treePath.replace(/^(\s|,)+|(\s|,)+$/g, '');
        formState.value.parentId = treePath.split(',').pop();
        defaultParentIds.value = treePath.split(',');
        formState.value.grade = parentInfo.grade + 1;
      } else {
        formState.value.grade = 1
      }
      if (!save && parentInfo.id) {
        MenuApi.findById({id: parentInfo.id}).then((res) => {
          if (res.success) {
            formState.value = res.data;
            if (formState.value.parentId === 0 || formState.value.parentId === '0') {
              defaultParentIds.value = [];
            } else {
              let treePath = res.data.treePath.replace(/^(\s|,)+|(\s|,)+$/g, '');
              defaultParentIds.value = defaultParentIds.value = treePath.split(',').filter((item) => item !== parentInfo.id);
            }
          }
        });
      }
    }
    formState.value.partitionId = pageSearch.partitionId;
  }).catch((error) => {
    console.log('error:', error);
  }).finally(() => {
    setSubLoading(false);
  });
}
//监听props.visible 值得变化
watch(() => props.drawer, v => {
  visible.value = v
})
defineExpose({
  initInfo,
})
</script>

<style scoped></style>
